package sort;

import java.util.Arrays;

/**
 * @author LLing
 * @className BubbleSort
 * @description: 冒泡排序实现
 * @date 2021/12/12 13:47
 */
public class BubbleSort {


    public static void main(String[] args) {
        int[] array = {3,6,3,7,12,3,13,56};
//        bubbleSort(array);
//        System.out.println(Arrays.toString(array));

//        newBubbleSort(array);
//        System.out.println(Arrays.toString(array));

        cocktailSort(array);
        System.out.println(Arrays.toString(array));
    }



    public static void bubbleSort(int[] array){

        for (int i = 0; i < array.length - 1; i++) {

            for (int j = 0; j < array.length -i - 1; j++) {
                int temp = 0;
                if(array[j]>array[j+1]){
                    temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;

                }
            }

        }

    }



    /**
     * 用布尔值标识有没有发生位置交换
     * @param array
     */
    public static void newBubbleSort(int[] array){

        for (int i = 0; i < array.length -1; i++) {
            //有序标记
            boolean isSort = true;
            System.out.println("这是第"+(i+1)+"轮排序");
            for (int j = 0; j < array.length - i - 1; j++) {
                int temp =0;
                if (array[j]>array[j+1]){
                    temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                    //有元素进行了交换，改成false
                    isSort = false;
                }
            }
            //本轮排序未发生元素交换，排序已经完成
            if (isSort){
                break;
            }
        }
    }


    /**
     * 鸡尾酒排序
     * @param array
     */
    public static void cocktailSort(int[] array){


        int temp = 0;
        for (int i = 0; i < array.length/2; i++) {
            System.out.println("这是第"+(i+1)+"轮排序");
            //是否有序标记，每一轮都是true;
            boolean isSort = true;
            //奇数轮，从左往右比较
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j]>array[j+1]){
                    temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                    //发生元素交换，标记为无序
                    isSort  = false;
                }
            }
            //有序，排序结束
            if (isSort){
                break;
            }
            isSort = true;
            //偶数轮从右往左比较
            for (int j = array.length - 1 - i; j >i; j--) {

                if (array[j]<array[j-1]){
                    temp = array[j];
                    array[j] = array[j-1];
                    array[j-1] = temp;
                    //发生元素交换，标记为无序
                    isSort  = false;
                }

            }

            if (isSort){
                break;
            }

        }

    }



}
